var that;
var timer;
var items = require('../../data/citydata.js');
var rightheight = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    letters: ['定位', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
    citys: [],
    city: " ",
    toView: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this,
    that.setData({
      citys: items.citys
    })
    wx.getLocation({
      success: function(res) {
        that.getCity(res.latitude, res.longitude)
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.dialog = this.selectComponent("#dialog");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var query = wx.createSelectorQuery();
    query.select('#right').boundingClientRect()
    query.exec(function (res) {
      rightheight = res[0].height;
    })
  },

  getCity: function(lat, lng) {
    const url = "https://api.map.baidu.com/reverse_geocoding/v3/";
    const param = {
      location: lat + "," + lng,
      output: "json",
      ak: "CEcGPUuy0DKl8mj1G87aSSnWIF10FxPp"
    };
    wx.request({
      url: url,
      data: param,
      success: function(res) {
        let city = res.data.result.addressComponent.city;
        // xx市 -> xx
        city = city.substring(0, city.length - 1);
        const district = res.data.result.addressComponent.district;
        const street = res.data.result.addressComponent.street;
        that.setData({
          city: city,
          district: district,
          street: street
        });
      }
    })
  },

  //右侧索引表点击事件
  letterclick: function (e) {
    var letter = e.currentTarget.dataset.letter;
    var isShow = that.dialog.getDialogState();
    if('定位' == letter){
      that.setData({
        toView: 'dw',
      })
    }else{
      this.showOrHideLetterDialog(isShow,letter,true);
      that.setData({
        toView: letter,
      })
    }
    console.log('letterclick letter : ' + letter);
  },

  startTime: function (autodimiss) {
    if (autodimiss){
      timer = setTimeout(function () {
        that.dialog.hideDialog();
      }, 1500)
    }
  },

  showOrHideLetterDialog: function(isShow,letter,autodimss) {
    if (!isShow) {
      that.dialog.setLetter(letter);
      that.dialog.showDialog();
      this.startTime(autodimss);
    } else {
      clearTimeout(timer);
      this.startTime(autodimss);
      that.dialog.setLetter(letter);
    }
  },

  selectcity: function(e) {
    var orgid = e.currentTarget.dataset.orgid
    var orgname = e.currentTarget.dataset.orgname
    wx.showToast({
      title: 'orgid : ' + orgid + ' orgname : ' + orgname,
      icon: 'none'
    })
    this.setData({
      city: orgname
    })
  },

  searchCity: function (e) {
    wx.navigateTo({
      url: `/pages/index/index?city=${this.data.city}`
    })
  }
})